package rfcomm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.List;
import java.util.Vector;

import javax.bluetooth.RemoteDevice;
import javax.microedition.io.StreamConnection;

public class Peer
{
    final String uuidgen = "1101";
    private Status status;
    private Server singleServer;
    private Cliente singleCliente;
    private Envelope envelope;
    BufferedReader br;
    //private int numeroConexao;

    public Peer()
    {
        status = Status.ON;
        envelope = new Envelope();
        singleServer = new Server( uuidgen, envelope, status );
        singleCliente = new Cliente( uuidgen, envelope, status );
        envelope.setToken( " " );
        br = new BufferedReader( new InputStreamReader( System.in ) );
        //numeroConexao = 0;
    }

    public Thread ThreadServer = new Thread() {
        public void run()
        {
            singleServer.connectAndRegisterRequest();
        }
    };

    public Thread ThreadCliente = new Thread() {
        public void run()
        {
            RemoteDevice rd = null;
            StreamConnection sc = null;
            List<PairNeighborConnection> paired;
            BufferedReader br;
            PrintWriter printWriter;
            Vector<RemoteDevice> list = singleCliente.listDevicesFounded();
            // int list_length = list.size();

            while( list.size() == 0 ) {
                System.out.println( "Peer not founded" );
                status.setStatus( false );
                try {
                    this.sleep( 20000 );
                    list = singleCliente.listDevicesFounded();
                } catch( InterruptedException e ) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            printInScreenDiscovered( list );
            paired = singleCliente.getListOfConnectedDevices();

            // while( numeroConexao < list_length ) {
            rd = selectDeviceFromList();
            sc = singleCliente.connectToDevice( rd );

            // numeroConexao++;
            br = readingStream( sc );
            printWriter = writingStream( sc );
            singleCliente.communication( br, printWriter );
            
            // }
        }
    };

    public void inicializarThreads()
    {
        hasStartWithToken();
        ThreadServer.start();
        ThreadCliente.start();
    }

    /**
     * Determine whether peer will start with token or not.
     */
    public void hasStartWithToken()
    {
        String line;
        System.out.println( "If I'm going to start with token press 1\n otherwise press 0." );
        try {
            line = br.readLine();
            if( line.trim().equals( "1" ) )
                envelope.setToken( "P" );
        } catch( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * From screen device list displayed choose one through the line command
     * 
     * @return RemoteDevice
     */
    public RemoteDevice selectDeviceFromList()
    {
        try {
            System.out.println( "Escolha o dispositivo" );
            String indexString = br.readLine();
            int index = Integer.parseInt( indexString );
            return singleCliente.getDeviceByIndex( index );
        } catch( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Given List of devices display them on screen
     * 
     * @param list List of devices
     */
    public void printInScreenDiscovered(
        Vector<RemoteDevice> list )
    {
        RemoteDevice rd;
        for( int i = 0; i < list.size(); i++ ) {
            rd = list.elementAt( i );
            System.out.println( ( i + 1 ) + " >" + rd.getBluetoothAddress() );
        }
    }

    public BufferedReader readingStream(
        StreamConnection sc )
    {
        BufferedReader bufr = null;
        try {
            bufr = new BufferedReader( new InputStreamReader( sc.openInputStream() ) );
        } catch( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bufr;
    }

    public PrintWriter writingStream(
        StreamConnection sc )
    {
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter( new OutputStreamWriter( sc.openOutputStream() ) );
        } catch( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return printWriter;
    }

    public static void main(
        String[] args )
    {
        Peer peer = new Peer();
        peer.inicializarThreads();
    }
}